package cn.tworice.monitor.controller;

import cn.tworice.common.vo.RequestResult;
import cn.tworice.monitor.service.MonitorService;
import cn.tworice.monitor.service.RequestFlowService;
import cn.tworice.monitor.vo.RequestInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

@RequestMapping("admin/monitor")
@RestController
@CrossOrigin
@Api(tags = "监控")
public class MonitorController {

    @Resource
    private MonitorService monitorService;

    @Resource
    private RequestFlowService requestFlowService;

    @GetMapping("log")
    @ApiOperation("获取数据库日志")
    public RequestResult log() {
        return RequestResult.success().appendData("monitor",monitorService.log());
    }

    @GetMapping("operation")
    @ApiOperation("获取操作日志")
    public RequestResult operation(){
        return RequestResult.success().appendData("monitor", monitorService.operation());
    }

    @GetMapping("flow")
    @ApiOperation("获取请求流")
    public RequestResult flow(){
        ConcurrentLinkedQueue<RequestInfo> queue = requestFlowService.getQueue();
        Map<String, Integer> ip = new LinkedHashMap<>();
        Map<String, Integer> time = new LinkedHashMap<>();
        for (RequestInfo requestInfo : queue) {
            String ipAddr = requestInfo.getIpAddr();
            if(ip.containsKey(ipAddr)){
                ip.put(ipAddr, ip.get(ipAddr)+ 1);
            }else{
                ip.put(ipAddr, 1);
            }

            String date = requestInfo.getDate();
            if(time.containsKey(date)){
                time.put(date, time.get(date)+ 1);
            }else{
                time.put(date, 1);
            }
        }
        return RequestResult.success().appendData("ip", ip).appendData("time",time);
    }

    @GetMapping("sql")
    @ApiOperation("获取SQL注入攻击记录")
    public RequestResult sql() {
        return RequestResult.success().appendData("sql", requestFlowService.getSqlMap());
    }

    @GetMapping("access")
    @ApiOperation("获取访问记录")
    public RequestResult access() {
        return RequestResult.success().appendData("access", requestFlowService.getAccessQueue());
    }

    @GetMapping("all")
    @ApiOperation("获取所有监控状态")
    public RequestResult all() {
        return RequestResult.success()
                .appendData("access",requestFlowService.getAccessQueue())
                .appendData("sql", requestFlowService.getSqlMap())
                .appendData("log",monitorService.log())
                .appendData("operation", monitorService.operation());
    }
}
